package cn.piggy.listener;

import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.NotNull;
import org.springframework.lang.Nullable;
import java.util.concurrent.CountDownLatch;

public class PiggyEventSourceListener extends EventSourceListener {

    private final CountDownLatch countDownLatch;
    public PiggyEventSourceListener(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
        boolean successful = response.isSuccessful();
        System.out.println("EventSourceListener --> onOpen --> "+successful);
    }

    @Override
    public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
        System.out.println(data);
    }

    @Override
    public void onClosed(@NotNull EventSource eventSource) {
        System.out.println("EventSourceListener --> onClosed");
        countDownLatch.countDown();
        eventSource.cancel();
    }

    @Override
    public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
        System.out.println("EventSourceListener --> onFailure");
        countDownLatch.countDown();
    }
}
